<?php

namespace App\Http\Controllers\admin\system;

use App\Http\Controllers\Controller;
use App\Models\product\ProductBelongModel;
use App\Models\product\ProductClassModel;
use App\Models\product\ProductCommissionRuleModel;
use App\Models\system\ConfigModel;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use lxs\api\ApiResponse;
use lxs\tools\Tools;

class ConfigureController extends Controller
{

    /**
     * 获取常规配置页面数据
     */
    public function getConventionData(): JsonResponse
    {
        $data['system'] = Tools::config('SYSTEM');
        $data['user'] = Tools::config('USER');
        $data['single'] = Tools::config('SINGLE');

        $data['system']['xcx_introduce_content_data'] = [];
        $data['single']['cancel_account_content_data'] = [];
        $data['single']['amount_difference_data'] = [];
        $data['single']['withdraw_rules_data'] = [];
        $data['single']['real_name_agreement_data'] = [];

        if ($data['system']['xcx_introduce_content']) {
            $data['system']['xcx_introduce_content'] = explode(',', $data['system']['xcx_introduce_content']);
            foreach ($data['system']['xcx_introduce_content'] as $k => $v) {
                $data['system']['xcx_introduce_content_data'][$k]['url'] = $v;
            }
        } else {
            $data['system']['xcx_introduce_content'] = [];
        }

        if ($data['single']['cancel_account_content']) {
            $data['single']['cancel_account_content'] = explode(',', $data['single']['cancel_account_content']);
            foreach ($data['single']['cancel_account_content'] as $k => $v) {
                $data['single']['cancel_account_content_data'][$k]['url'] = $v;
            }
        } else {
            $data['single']['cancel_account_content'] = [];
        }

        if ($data['single']['amount_difference']) {
            $data['single']['amount_difference'] = explode(',', $data['single']['amount_difference']);
            foreach ($data['single']['amount_difference'] as $k => $v) {
                $data['single']['amount_difference_data'][$k]['url'] = $v;
            }
        } else {
            $data['single']['amount_difference'] = [];
        }

        if ($data['single']['withdraw_rules']) {
            $data['single']['withdraw_rules'] = explode(',', $data['single']['withdraw_rules']);
            foreach ($data['single']['withdraw_rules'] as $k => $v) {
                $data['single']['withdraw_rules_data'][$k]['url'] = $v;
            }
        } else {
            $data['single']['withdraw_rules'] = [];
        }

        if ($data['single']['real_name_agreement']) {
            $data['single']['real_name_agreement'] = explode(',', $data['single']['real_name_agreement']);
            foreach ($data['single']['real_name_agreement'] as $k => $v) {
                $data['single']['real_name_agreement_data'][$k]['url'] = $v;
            }
        } else {
            $data['single']['real_name_agreement'] = [];
        }

        return ApiResponse::success('获取常规配置页面数据成功', $data);
    }


    /**
     * 更新常规配置
     */
    public function conventionFormSubmit(): JsonResponse
    {
        $post['system']['wechat_logo'] = request()->input('system_wechat_logo');
        $post['system']['curstomer_qrcode'] = request()->input('system_curstomer_qrcode');
        $post['system']['prr'] = request()->input('system_prr');
        $post['system']['xcx_introduce_content'] = request()->input('system_xcx_introduce_content');
        $post['system']['icon_assistant'] = request()->input('system_icon_assistant');
        $post['system']['icon_user'] = request()->input('system_icon_user');
        $post['system']['icon_relating'] = request()->input('system_icon_relating');

        $post['user']['cancel_time'] = request()->input('user_cancel_time');
        $post['user']['withdraw_commission'] = request()->input('user_withdraw_commission');
        $post['user']['withdraw_day'] = request()->input('user_withdraw_day');

        $post['single']['cancel_account_content'] = request()->input('single_cancel_account_content');
        $post['single']['amount_difference'] = request()->input('single_amount_difference');
        $post['single']['withdraw_rules'] = request()->input('single_withdraw_rules');
        $post['single']['real_name_agreement'] = request()->input('single_real_name_agreement');

        if ($post['system']['xcx_introduce_content']) {
            $post['system']['xcx_introduce_content'] = implode(',', $post['system']['xcx_introduce_content']);
        }

        if ($post['single']['cancel_account_content']) {
            $post['single']['cancel_account_content'] = implode(',', $post['single']['cancel_account_content']);
        }

        if ($post['single']['amount_difference']) {
            $post['single']['amount_difference'] = implode(',', $post['single']['amount_difference']);
        }

        if ($post['single']['withdraw_rules']) {
            $post['single']['withdraw_rules'] = implode(',', $post['single']['withdraw_rules']);
        }

        if ($post['single']['real_name_agreement']) {
            $post['single']['real_name_agreement'] = implode(',', $post['single']['real_name_agreement']);
        }

        foreach ($post as $k => $v) {
            foreach ($v as $kk => $vv) {
                $map = ['type' => $k, 'name' => $kk];
                $data = ['value' => $vv];
                $query = ConfigModel::where($map);
                if (count($query->get()) > 0) {
                    $query->update($data);
                } else {
                    $query->create($data);
                }
            }
        }

        return ApiResponse::success('更新常规配置成功');
    }


    /**
     * 获取产品提成设置页面数据
     */
    public function getProductCommissionData(): JsonResponse
    {
        $lists = ProductBelongModel::where('deleted_at', 0)->get()->toArray();
        $lists = array_map(function ($item) {
            $item['hasChildren'] = true;
                $item['children'] = ProductClassModel::select('id as class_id', 'class_name as belong_name', 'create_at')
                    ->where('deleted_at', 0)
                    ->get()
                    ->toArray();
                $item['children'] = array_map(function ($items) use ($item) {
                    $items['belong_id'] = $item['id'];
                    $items['commission_rate'] = ProductCommissionRuleModel::where('belong_id', $item['id'])
                        ->where('class_id', $items['class_id'])
                        ->where('deleted_at', 0)
                        ->value('commission_rate') ?? 0;
                    return $items;
                }, $item['children']);
            return $item;
        }, $lists);
        return ApiResponse::success('获取产品提成设置页面数据成功', $lists);
    }


    /**
     * 产品提成设置表单提交
     */
    public function productClassProductFormSubmit(): JsonResponse
    {
        $post = request()->input();
        try {
            DB::beginTransaction();

            $data = [
                'commission_rate' => $post['commission_rate'],
                'belong_id' => $post['belong_id'],
                'class_id' => $post['class_id']
            ];
            $commission_rule = ProductCommissionRuleModel::where('belong_id', $post['belong_id'])
                ->where('class_id', $post['class_id'])
                ->where('deleted_at', 0)
                ->first();
            if ($commission_rule) {
                $commission_rule->where('id', $commission_rule->id)->update($data);
            } else {
                ProductCommissionRuleModel::create($data);
            }

            DB::commit();
            return ApiResponse::success('提交成功');
        }  catch (\Exception $e) {
            DB::rollBack();
            Log::error(time() . '产品提成设置表单提交: ' . $e->getMessage() . $e->getLine() . $e->getFile());
            return ApiResponse::error('提交失败');
        }

    }


}
